//
//  KZRefreshTableViewController.m
//  xiaorizi
//
//  Created by kun on 15/10/23.
//  Copyright © 2015年 origin. All rights reserved.
//

#import "KZRefreshTableViewController.h"
#import "MJRefresh.h"
#import "AFNetworking.h"

#define DATALOCAL 1

@interface KZRefreshTableViewController ()

@end

@implementation KZRefreshTableViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //初始化必要的数据
  
    self.data = [NSMutableArray new];
    
#ifdef DATALOCAL
    
    [self loadDataFromCache];
#else
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.cachePath]) {
        
        [self loadDataFromCache];
    }
    else {
        [self loadDataFromServer];
    }
#endif

    
    
}


//缓存加载数据

- (void)downloadDataPath
{


}

-(void)loadDataFromCache
{
    
#ifdef DATALOCAL
    //1读取json数据
    NSString *stringData = [self JsonModelPath];
    
    NSData *fileData = [NSData dataWithContentsOfFile:stringData];

    
    [fileData writeToFile:self.cachePath atomically:YES];
    //获取二进制数据
    
    
   // NSData *fileData = [NSData dataWithContentsOfFile:self.cachePath];
    
    NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableContainers error:nil];
    if(dataDic == nil) return;
    
    //数据分成解析获取内容
    NSArray *arrayData = [self createDataArray:dataDic];
    
    for(id node in arrayData)
    {
        id obj = [self createDataWithNode:node];
        
        [self.data addObject:obj];
    }
    NSLog(@"--->count : %ld",self.data.count);
    
#else
    //获取二进制数据
    NSData *fileData = [NSData dataWithContentsOfFile:self.cachePath];
    
    if(!fileData) return;
    
    //将二进制json 数据解析
    NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableContainers error:nil];
        
    if(dataDic == nil) return;
    
    //数据分成解析获取内容
    NSArray *arrayData = [self createDataArray:dataDic];
    
    for(id node in arrayData)
    {
        id obj = [self createDataWithNode:node];
        [self.data addObject:obj];
    }
#endif
    
    [self.tableView reloadData];
    
}

//用于子类重写该方法

-(NSString *)JsonModelPath
{
    return nil;
}

-(NSArray *)createDataArray:(NSDictionary *)dic
{
    return nil;
}

- (id)createDataWithNode:(id)node
{
    return nil;
}

//服务器抓取数据
-(void)loadDataFromServer
{
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    
    [manger GET:self.url parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        //停止头部刷新
        [self.tableView.header endRefreshing];
        
        //添加数据
        if(responseObject)
        {
            
            //删除之前的数据
            [[NSFileManager defaultManager] removeItemAtPath:self.cachePath error:nil];
            [self.data removeAllObjects];
            
           // [[NSFileManager defaultManager] setValue:operation.responseData forKeyPath:self.cachePath];
            [operation.responseData writeToFile:self.cachePath atomically:NO];
            
            [self loadDataFromCache];
            
            //从新加载tableView
            //[self.tableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"--->数据请求失败");
        [self.tableView.header endRefreshing];
        
    }];
    
}


//设置刷新类型

-(void)setRefreshType:(FLRefreshType)refreshType
{
    _refreshType = refreshType;
    
    if(refreshType & FLRefreshTypeHeader)
    {
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    }
    
    if(refreshType & FLRefreshTypeFooter)
    {
        
        self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    }
}


//头部刷新是从服务器从新刷新
- (void) headerRefresh
{
    [self loadDataFromServer];
}

#warning 1 这里下拉刷新没有添加
//下拉刷新
- (void) footerRefresh
{
    
}
    
    
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.data.count;
}





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
